package dbs

import (
	"fmt"
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"k8s.io/utils/env"
)

// 假设你的数据库连接信息
const (
	dbParam = "charset=utf8mb4&parseTime=True&loc=Local" // 替换为你的数据库连接信息
)

var db *gorm.DB

func connectDb() {
	dbDsn := fmt.Sprintf(
		"%s:%s@tcp(%s)/%s?%s",
		env.GetString("DB_USER", "root"),
		env.GetString("DB_PASSWORD", "sde!23$sW"),
		env.GetString("DB_HOST", "61.147.99.81:32002"),
		env.GetString("DB_NAME", "swu"),
		env.GetString("DB_PARAM", dbParam),
	)

	var err error
	db, err = gorm.Open(mysql.Open(dbDsn), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect to database:", err)
	}
	log.Println("Database connected with GORM")
}

func GetDB() *gorm.DB {
	if db == nil {
		connectDb()
	}
	return db
}
